﻿                                                                                                                                                            using MyModule.ManageSheep;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace MyModule.Breeding
{
    public class AppearanceService : ApplicationService, IAppearanceService
    {
        private readonly IRepository<Appearance, int> _weighInfoRepository;
        private readonly IRepository<VarietyInfo, int> _varietyInfoRepository;
        private readonly IHttpClientFactory _httpClientFactory;

        public AppearanceService(IRepository<Appearance, int> weighInfoRepository, IRepository<VarietyInfo, int> varietyInfoRepository,IHttpClientFactory httpClientFactory)
        {
            _weighInfoRepository = weighInfoRepository;
            _varietyInfoRepository = varietyInfoRepository;
            _httpClientFactory = httpClientFactory;
    }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="appearanceDTO"></param>
        /// <returns></returns>
        public async Task<ResultDto<AppearanceDTO>> CreateAsync(AppearanceDTO appearanceDTO)
        {
            var list = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Earbugles == appearanceDTO.Earbugles);
            if (list == null)
            {
                Appearance appearance = new Appearance();
                appearance.Vid = appearanceDTO.Vid;
                appearance.Asex = appearanceDTO.Asex;
                appearance.Adate = appearanceDTO.Adate;
                appearance.Abuildings = appearanceDTO.Abuildings;
                appearance.Acolumns = appearanceDTO.Acolumns;
                appearance.Earbugles = appearanceDTO.Earbugles;
                appearance.Aocclude = appearanceDTO.Aocclude;
                appearance.Ahair = appearanceDTO.Ahair;
                appearance.Apigmentation = appearanceDTO.Apigmentation;
                appearance.Ahoof = appearanceDTO.Ahoof;
                appearance.Amouth = appearanceDTO.Amouth;
                appearance.Ahorn = appearanceDTO.Ahorn;
                appearance.Adistribution = appearanceDTO.Adistribution;
                var result = await _weighInfoRepository.InsertAsync(appearance);
                var listCount = ObjectMapper.Map<Appearance, AppearanceDTO>(result);
                if (listCount != null)
                {
                    return new ResultDto<AppearanceDTO>() { Code = 200, Message = "添加成功" };
                }
                else
                {
                    return new ResultDto<AppearanceDTO>() { Code =500, Message = "添加失败" };
                }
            }
            else 
            {
                return new ResultDto<AppearanceDTO>() { Code = 501 };
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Aid"></param>
        /// <returns></returns>
        public async Task DeleteAsync(int Aid)
        {
            await _weighInfoRepository.DeleteAsync(Aid);
        }

        /// <summary>
        /// 显示分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<AppearanceVarietyDTO>> GetListAppAsync(int Vid,string? Earbugles)
        {

            var result = await _weighInfoRepository.ToListAsync();
            var varietie = await _varietyInfoRepository.ToListAsync();
            var list = (from a in result
                        join c in varietie on a.Vid equals c.Id
                        select new AppearanceVarietyDTO
                        {
                           Id = a.Id,
                           Vid = c.Id,
                           Adate = a.Adate,
                           Vname = c.Vname,
                           Asex  = a.Asex,
                           Abuildings = a.Abuildings,
                           Acolumns = a.Acolumns,
                           Earbugles = a.Earbugles,
                           Aocclude = a.Aocclude,
                           Ahair = a.Ahair,
                           Apigmentation = a.Apigmentation,
                           Ahoof = a.Ahoof,
                           Amouth = a.Amouth,
                           Ahorn = a.Ahorn,
                           Adistribution = a.Adistribution
                        }).ToList();
            if (!string.IsNullOrEmpty(Earbugles))
            {
                list = list.Where(x => x.Earbugles == Earbugles).ToList();
            }
            if (Vid != 0)
            {
                list = list.Where(x => x.Vid == Vid).ToList();
            }
            return list.OrderByDescending(x => x.Id).ToList();
        }
        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AppearanceDTO> GetListAsync(int id)
        {
            var result = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Id == id);
            return ObjectMapper.Map<Appearance, AppearanceDTO>(result);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="appearanceDTO"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task<ResultDto<AppearanceDTO>> UpdateAsync(AppearanceDTO appearanceDTO)
        {
                var result = await _weighInfoRepository.FindAsync(appearanceDTO.Id);
                if (result == null)
                {
                    return new ResultDto<AppearanceDTO>() { Code = 500 };
                }
                ObjectMapper.Map(appearanceDTO, result);
                var count = await _weighInfoRepository.UpdateAsync(result);
                var listCount = ObjectMapper.Map<Appearance, AppearanceDTO>(count);
                if (listCount != null)
                {
                    return new ResultDto<AppearanceDTO>() { Code = 200, Message = "修改成功" };
                }
                else
                {
                    return new ResultDto<AppearanceDTO>() { Code = 500, Message = "修改失败" };
                }
            
        }
        /// <summary>
        /// 毛发
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetAhairInfo() 
        {
            List<object> list = new List<object>();

            foreach (var item in Enum.GetValues<Ahair>()) 
            {
               list.Add( new {
                   label =item.ToString(),
                   value =(int)item
                });
            }
            return list;
        }
        /// <summary>
        /// 色斑
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetApigmentationInfo()
        {
            List<object> list = new List<object>();

            foreach (var item in Enum.GetValues<Apigmentation>())
            {
                list.Add(new
                {
                    label = item.ToString(),
                    value = (int)item
                });
            }
            return list;
        }

        /// <summary>
        /// 蹄颜色
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetAhoofInfo()
        {
            List<object> list = new List<object>();

            foreach (var item in Enum.GetValues<Ahoof>())
            {
                list.Add(new
                {
                    label = item.ToString(),
                    value = (int)item
                });
            }
            return list;
        }

        /// <summary>
        /// 嘴颜色
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetAmouthInfo()
        {
            List<object> list = new List<object>();

            foreach (var item in Enum.GetValues<Amouth>())
            {
                list.Add(new
                {
                    label = item.ToString(),
                    value = (int)item
                });
            }
            return list;
        }
        /// <summary>
        /// 脂肪分布
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetAdistributionInfo()
        {
            List<object> list = new List<object>();

            foreach (var item in Enum.GetValues<Adistribution>())
            {
                list.Add(new
                {
                    label = item.ToString(),
                    value = (int)item
                });
            }
            return list;
        }

        /// <summary>
        /// 品相耳号下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<DropdownItemDto>> GetAppearEarbugles()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/earoverbit/earoverbits");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<EarOverbit>>(jsonString);
            // 查询已使用的数据的 Id 列表
            var usedDataIds = _weighInfoRepository.GetListAsync().Result.Select(d => d.Earbugles).ToList();
            // 查询所有数据，并过滤已使用的数据
            var list = data.Where(d => !usedDataIds.Contains(d.OverbitName)).ToList();
            // 转换为 DropdownItemDto 并返回
            return list.Select(d => new DropdownItemDto { Id = d.Id, Name = d.OverbitName }).ToList();
        }



    }
}
